import { action, observable, computed } from "mobx";
import { WeaForm } from "comsMobx";
import Search from '.';
import * as API from "../../apis/resource";
import _ from "lodash";
import { message, Button } from 'antd';
import { WeaLocaleProvider,WeaTools } from "ecCom";
import { getDateBetweenDates, isInWeek, getHourBetweenDates, addDay } from "../../util/dateUtil";
import CardStore from '../card/index';
const getLabel = WeaLocaleProvider.getLabel;
const getTop = WeaTools.WindowFunc.getTop;
import jQuery from 'jquery';

export default class ViewResouceStore {
  @observable form = new WeaForm();
  @observable loading: boolean = false;
  @observable rightMenus: any = [];
  @observable customid = '';//查询id
  @observable currentdate;
  @observable resourceParams: any = { bywhat: 0 };
  @observable resourcesList: any = [];
  @observable useMap: any = {};   //占用情况
  @observable timeType = 'day';
  @observable hasUrlByWhat: boolean = false;  //判断url是否含有bywaht，bywhat优先级最高
  @observable duration = 0;
  @observable conHeight = 0;
  @observable tabHeight = 0;
  @observable spinisload = false;
  // @observable listHeight = 0;
  @observable moduls = '';     //解析是否在前端的参数
  @observable resourceId = '';
  searchParam = { customid: '', datasqlwhere: '' };
  resourceFieldName = '';//资源字段
  @observable modename = '';//模块名称
  @observable createUrl = '';//新增地址
  @observable oriCreateUrl = '';//原始新增地址
  @observable visible: boolean = false;
  @observable currentpage = 1;//当前页数
  @observable total = 0;//总记录
  @observable windowTitle = '';//页面标题
  @observable showMoreVisible: boolean = false;//是否要显示显示更多
  @observable startHour = 0;//时间起始
  @observable endHour = 23;//时间结束
  @observable dspunit = 1;//占用时间单位
  @observable usedcolor = '#1372AA';//占用颜色
  @observable conflictedcolor = '#B3110B';//冲突颜色
  @observable weekstart = '1';//周开始日期  1周日 2周一
  @observable fields : any = {};//配置信息
  @observable dragref :any;//周开始日期
  @observable conditions :any=[];//查询条件
  @observable queryparm : any = {};//查询条件参数(点击小漏斗的参数)
  sqlwhere = '';

  @observable card = new CardStore();


  @action
  updateHeight = (conHeight, tabHeight, listHeight) => {
    this.conHeight = conHeight;
    this.tabHeight = tabHeight;
    // this.listHeight = listHeight; 
    let quickheight=jQuery(".list-container .wea-tab-search-ad").height();//查询列表快捷搜索高度
    let countheight=jQuery(".list-container .cube-list-countContainer").height();//统计字段高度
    quickheight=quickheight==null?0:quickheight;
    countheight=countheight==null?0:countheight;
    Search.viewResHeight = listHeight;
    // Search.listHeight=listHeight-quickheight-countheight-85;
  }


  @action
  updateParams = (params: any) => {
    this.customid = params.customid;
    Search.clear(); //先清空查询的数据
    API.getCurrentDate({}).then(action(({ status, error, currentDate }) => {
      if (status == '1') {
        if(params.menuIds){
          this.moduls = params.menuIds;
        }
        this.currentdate = currentDate;
        this.resourceParams = { resourceId: params.customid, bywhat: this.resourceParams.bywhat, currentdate: currentDate };
        this.query(this.resourceParams);
      }
    }));
  }

  @action
  query = (params = {}) => {
    let that = this;
    this.currentpage=1;
    // Search.forceUpdate=false;
    this.loading = true;
    let iscustomsearch=jQuery.isEmptyObject(this.queryparm)?false:true;
    this.resourceParams = { ...this.resourceParams, ...params};
    let timeType: string;
    switch (Number(this.resourceParams.bywhat)) {
      case 2: timeType = "month"; break;
      case 3: timeType = "week"; break;
      case 4: timeType = "day"; break;
      default: timeType = "day";
    }
    let endparm={...this.resourceParams,...this.queryparm,iscustomsearch:iscustomsearch};
    this.updateTimeType(timeType)
    API.getResourcesInfo({ ...endparm, sqlwhere: encodeURIComponent(this.sqlwhere) }).then(action(({ status, error, datainfo, datasqlwhere,conditions}) => {
      if (status == '1') {
        this.fields=datainfo.fields;
        this.modename = datainfo.fields.modename;
        if(this.moduls == ""&&window.location.href.indexOf('wui/index.html')==-1){
          this.windowTitle = datainfo.fields.resourceName;
        }
        this.createUrl =datainfo.fields.createUrl ||""; //只针对建模的卡片处理，其他的都正常iframe显示
        if(datainfo.fields.createUrl&&datainfo.fields.createUrl.indexOf("/spa/cube/index.html#/main/cube/card") > -1){
          this.createUrl = datainfo.fields.createUrl.replace("html", "jsp") ;
        }
        this.oriCreateUrl=this.createUrl;
        this.resourceFieldName = datainfo.fields.resourceFieldName;
        this.searchParam = { customid: datainfo.fields.customSearchId, datasqlwhere };
        this.startHour=parseInt(datainfo.fields.timerangestart);
        this.endHour=parseInt(datainfo.fields.timerangeend);
        this.dspunit=parseInt(datainfo.fields.dspunit);
        this.usedcolor=datainfo.fields.usedcolor;
        this.conflictedcolor=datainfo.fields.conflictedcolor;
        this.weekstart=datainfo.fields.weekstart;
        this.search(this.searchParam);
        this.duration=(timeType == 'day' && this.dspunit > 0) ? 60 / this.dspunit : 0;
        const { ids, names,titles } = datainfo;
        let resourceList: any = [];
        if (this.resourceParams.bywhat === 0) {
          let timeType = "day";
          switch (datainfo.fields.defaultByWhat) {
            case "2": timeType = "month"; break;
            case "3": timeType = "week"; break;
            case "4": timeType = "day"; break;
            default: timeType = "day";
          }
          this.resourceParams.bywhat = datainfo.fields.defaultByWhat;
          this.updateTimeType(timeType)
        }
        this.getRightMenus();
        ids && _.isArray(ids) && ids.map((id, index) => {
          resourceList.push({
            "name": names[index],
            "id": id,
            "title": titles[index],
          })
        })
        that.resourcesList = resourceList;
        this.total=datainfo.total;
        let useMap=this.showSet(datainfo);
        that.useMap = useMap;
        that.loading = false;
      } else {
        message.error(getLabel(383746, '请求失败') + "：" + error);
      }
      this.conditions=conditions;
      this.loading = false;
    }))

  }

  @action
  search = (params = {}) => {
    Search.isInnerTab = true;
    Search.params = {};
    Search.reloadSearch({ ...params, datasqlwhere:params['datasqlwhere'] });
  }

  @action
  updateTimeType = (type: string) => {
    this.timeType = type;
  }

  @action
  getRightMenus = () => {
    const rightArr = [{
      key: 'month',
      content: getLabel(18517, '月使用情况'),
      icon: <i className="icon-coms-New-schedule" />
    }, {
      key: 'week',
      content: getLabel(18516, '周使用情况'),
      icon: <i className="icon-coms-New-schedule" />
    }, {
      key: 'day',
      content: getLabel(18515, '日使用情况'),
      icon: <i className="icon-coms-New-schedule" />
    }]
    if (this.createUrl) {
      rightArr.push({
        key: 'add',
        content: getLabel(82, '新建') +' '+ this.modename,
        icon: <i className="icon-coms-New-Flow" />
      });
    }
    this.rightMenus = rightArr;
  }
  @action
  onAdd = (parms?) => {
    let urlparm='';
    if(parms){
      const {id,startDate,startTime,endDate,endTime,startdatetime,enddatetime}=parms;
      urlparm=`&field${this.fields.resourceFieldId}=${id}`;
      if(this.fields.startaloneOrcombination=='2'){
        urlparm+=`&field${this.fields.startDateTimeFieldId}=${startdatetime}`;
      }else{
        urlparm+=`&field${this.fields.startDateFieldId}=${startDate}&field${this.fields.startTimeFieldId}=${startTime}`;
      }
      if(this.fields.endaloneOrcombination=='2'){
        urlparm+=`&field${this.fields.endDateTimeFieldId}=${enddatetime}`;
      }else{
        urlparm+=`&field${this.fields.endDateFieldId}=${endDate}&field${this.fields.endTimeFieldId}=${endTime}`;
      }
      this.createUrl=this.oriCreateUrl.replace(/\$begindate\$/ig,endDate).replace(/\$begintime\$/ig,startTime)
      .replace(/\$enddate\$/ig,endDate).replace(/\$endtime\$/ig,endTime).replace(/\$resourceid\$/ig,id);
    }else{
      this.createUrl=this.oriCreateUrl;
    }
    if (this.createUrl.indexOf("/spa/cube/index.jsp#/main/cube/card") > -1) {
      this.card.isInline = true;
      if (!this.card) {
        this.card = new CardStore();
      }
      let newurl=this.createUrl;
      if(urlparm!=''){
        newurl+=urlparm;
      }
      this.card.reloadSearch(this.getQuery(newurl));
      getTop().document.addEventListener('mousedown', this.card.quickEditStore.handleClickOutSide, true);
    }else{
      const lastofnum = this.createUrl.lastIndexOf('?');
      let parms=this.getQuery(this.createUrl);
      this.createUrl = this.createUrl.slice(0,lastofnum)
      if(!jQuery.isEmptyObject(parms)){
        this.createUrl+="?";
        let i=0;
        for (var val in parms) {
          if(i!=0){
            this.createUrl+="&"
          }
          i++;
          this.createUrl+=val+"="+parms[val]
        }
      }
        //流程页面的话调整新窗口打开   /spa/workflow/index_form.jsp
        const wfUrl = ['/spa/workflow/static4form/index.html', '/spa/workflow/index_form.jsp'];
        if (this.createUrl.indexOf(wfUrl[0]) > -1 || this.createUrl.indexOf(wfUrl[1]) > -1) {
          window.open(this.createUrl, '_blank');
          return;
        }
    }
    this.visible = true;
  }

  @action
  getQuery = (href: string) => {
    const lastofnum = href.lastIndexOf('?');
    href = href.slice(lastofnum);
    const query = href.split('?')[1];
    const querys = query.split("&");
    const queryObj: any = {};
    querys.map(q => {
      const [name, value] = q.split("=");
      var reg = /\$begindate\$|\$begintime\$|\$enddate\$|\$endtime\$|\$resourceid\$/i; 
      if(value.match(reg)!=null){
        return;
      }
      _.set(queryObj, name, value);
    });
    queryObj.istree = true;
    return queryObj;
  }

  @action
  getMore = () => {
    this.spinisload=true;
    this.currentpage++;
    let iscustomsearch=jQuery.isEmptyObject(this.queryparm)?false:true;
    let parm={...this.resourceParams,currentpage:this.currentpage,...this.queryparm,iscustomsearch:iscustomsearch}
    API.getResourcesInfo({ ...parm, sqlwhere: encodeURIComponent(this.sqlwhere) }).then(action(({ status, error, datainfo, datasqlwhere }) => {
        if (status == '1') {
          const { ids, names,titles } = datainfo;
          // Search.forceUpdate=true;
          let resourceList: any = [];
          ids && _.isArray(ids) && ids.map((id, index) => {
            resourceList.push({
              "name": names[index],
              "id": id,
              "title": titles[index],
            })
          })
          this.resourcesList=this.resourcesList.concat(resourceList);
          let useMap=this.showSet(datainfo);
          this.useMap ={...this.useMap,...useMap};
          this.loading = false;
          
      }
      this.spinisload=false;
    }))
  }


  showSet=(datainfo)=>{
    if(this.resourcesList.length<this.total){
      this.showMoreVisible=true;
    }else{
      this.showMoreVisible=false;
    }
    let useMap: any = {};
    datainfo.ids.forEach(item => {
      let rinfo = datainfo.resourceInfo[item];
      let mydata = {};
      rinfo.forEach(element => {
        let startDate = element[datainfo.fields.startDateFieldName];
        let endDate = element[datainfo.fields.endDateFieldName];
        let startTime = element[datainfo.fields.startTimeFieldName];
        let endTime = element[datainfo.fields.endTimeFieldName];
        let title = element[datainfo.fields.titleFieldName];
        let content = element[datainfo.fields.contentFieldName];

        let startDateTime = element[datainfo.fields.startDateTimeFieldName];
        let startaloneOrcombination = datainfo.fields.startaloneOrcombination;
        let endDateTime = element[datainfo.fields.endDateTimeFieldName];
        let endaloneOrcombination = datainfo.fields.endaloneOrcombination;

        if(startaloneOrcombination == '2'){
          startDate=startDateTime.substring(0, 10);
          startTime=startDateTime.substring(11);
        }
        if(endaloneOrcombination == '2'){
          endDate=endDateTime.substring(0, 10);
          endTime=endDateTime.substring(11);
        }

        if (this.resourceParams['bywhat'] == '2') {//月
          let datas = getDateBetweenDates(startDate, endDate);
          datas.forEach(item => {
            let t = mydata[item] ? mydata[item].title : [];
            t.push([getLabel(229, '标题')+'：' + title, getLabel(124948, '时间段')+'：' + startDate + ' ' + startTime + ' - ' + endDate + ' ' + endTime, getLabel(131393, '内容')+'：' + content]);
            let m = mydata[item] ? mydata[item].meetings : [];
            m.push({ name: title, id: element.id });
            mydata[item] = { title: t, meetings: m };
          });
        } else if (this.resourceParams['bywhat'] == '3') {//周
          let datas = getDateBetweenDates(startDate, endDate);
          datas.forEach(item => {
            if (isInWeek(this.resourceParams['currentdate'], this.resourceParams['movedate'], item,this.weekstart)) {//判断当前日期是否本周日期
              let t = mydata[item] ? mydata[item].title : [];
              t.push([getLabel(229, '标题')+'：' + title, getLabel(124948, '时间段')+'：' + startDate + ' ' + startTime + ' - ' + endDate + ' ' + endTime, getLabel(131393, '内容')+'：' + content]);
              let m = mydata[item] ? mydata[item].meetings : [];
              m.push({ name: title, id: element.id });
              mydata[item] = { title: t, meetings: m };
            }
          });
        } else if (this.resourceParams['bywhat'] == '4') {//日
          let hour = getHourBetweenDates(this.resourceParams['currentdate'], this.resourceParams['movedate'], startDate, startTime, endDate, endTime,this.dspunit);
          hour.forEach(i => {
            let t = mydata[i] ? mydata[i].title : [];
            t.push([getLabel(229, '标题')+'：' + title, getLabel(500371, '开始时间')+'：' + startDate + ' ' + startTime ,getLabel(500372, '结束时间')+'：' + endDate + ' ' + endTime, getLabel(131393, '内容')+'：' + content]);
            let m = mydata[i] ? mydata[i].meetings : [];
            m.push({ name: title, id: element.id });
            mydata[i] = { title: t, meetings: m };
          });
        }
      });
      const mydatakeys = _.keys(mydata);
      let info: any = [];
      for (let i = 0; i < mydatakeys.length; i++) {
        const key = mydatakeys[i];
        const value = mydata[key];
        const bgcolor = value.title.length > 1 ?this.conflictedcolor :this.usedcolor
        let intkey=parseInt(key);
        let  dspunittime= Math.floor(intkey)+''==key?":00":":30";
        info.push({
          bgcolor: bgcolor,
          content: value.title.length,
          date: key,
          time: Math.floor(intkey) + dspunittime,
          fontcolor: "",
          meetings: value.meetings,
          title: value.title
        });
      }
      useMap[item] = info;
    });
    return useMap;
  }

   /*拖曳结束*/
   dragChooseEnd = (dragState, activeCellProps) => {
    this.dragref&&this.dragref.clear();
    let { startProps, endProps } = dragState;
    let startTime = startProps.startTime;
    let endTime = endProps.endTime;
    if(endTime < startTime){
      startTime=endProps.startTime;
      endTime=startProps.endTime;
    }
    let id = startProps.room.id;
    let date = this.resourceParams['currentdate'];
    let movedate = this.resourceParams['movedate'];
    if(movedate){
       date=addDay(date,movedate);
    }
    let startdatetime=date+" "+startTime;
    let enddatetime=date+" "+endTime;
    let parms = { "startDate": date, "startTime": startTime, "endDate": date, "endTime": endTime, "id": id ,startdatetime:startdatetime,enddatetime:enddatetime};
    this.onAdd(parms);
    // if (this.createUrl.indexOf("/spa/cube/index.jsp#/main/cube/card") > -1) {
    // }else{
    //   this.visible = true;
    // }
  }



  @computed
  get quickButtons(): any[] {
    const quickRightMenus = this.card.cardTab.rightMenus.map(m => ({
      ...m,
      disabled: this.card.cardTab.disabled
    }));;
    return quickRightMenus.map(d => {
      return <Button type="primary"
        onClick={() => {
          if (d.function.startsWith('javascript:toDel(')) {
            this.card.Actions.runCustomAction(d.key, () => { window['cubeStore'].cubeViewResource.visible = false; });
          } else {
            this.card.Actions.runCustomAction(d.key);
          }
        }} >
        {d.content}
      </Button>
    });
  }
}
